<?php

namespace common\observer;

use common\model\TaskModel;
use support\SingletonTrait;
use common\model\EntityModel;
use common\service\CommonService;
use Throwable;
use teamones\dbeventObserver\interfaces\SplSubject;
use teamones\dbeventObserver\interfaces\SplObserver;

/**
 * 实体修改剧集 同步到任务
 */
class EntityChangeEpisodeCodeSyncToTask implements SplObserver
{
    use SingletonTrait;

    public $syncFields = 'initial_episode_code';

    /**
     * @param SplSubject $subject
     * @return void
     */
    function update(SplSubject $subject): void
    {
        $entity = $subject->getSubjectData();
        $updateData = $subject->getSplUpdateData();

        // 是否修改了剧集
        if (!in_array($this->syncFields, array_keys($updateData))) {
            return;
        }
        if (empty($entity['initial_episode_code'])) {
            return;
        }
        $episodeData = model(EntityModel::class)
            ->where(['project_id' => $entity['project_id'], 'module_id' => module_by_code('episode')['id'], 'code' => $entity['initial_episode_code']])
            ->field('id')
            ->find();
        if (empty($episodeData['id'])) {
            return;
        }
        $taskData = model(TaskModel::class)
            ->where(['project_id' => $entity['project_id'], 'entity_id' => $entity['id'], 'step_type' => ['IN', 'step,step_category']])
            ->field('id,episode_id')
            ->select();
        $batchUpdateData = [];
        if (empty($taskData)) {
            return;
        }
        foreach ($taskData as $value) {
            if ($value['episode_id'] == $episodeData['id']) {
                continue;
            }
            $batchUpdateData[] = [
                'id' => $value['id'],
                'episode_id' => $episodeData['id'],
            ];
        }

        if (empty($batchUpdateData)) {
            return;
        }
        try {
            CommonService::instance('task')
                ->commonBatchUpdate($batchUpdateData, module_by_code('task'), false);
        } catch (Throwable $e) {
            trace(format_exception_info($e), 'ERR');
        }
    }
}
